package com.lenovo.smarttraffic.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.InitApp;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.UserLogin;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;

import java.util.Map;

/**
 * @author Amoly
 * @date 2019/4/11.
 * description：
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private EditText mEditTextName;
    private EditText mEditTextPassword;
    private TextInputLayout mTextInputLayoutName;
    private TextInputLayout mTextInputLayoutPwd;
    private CheckBox keep_pwd, auto_login;

    private String url = "user_login";


    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolBar(findViewById(R.id.toolbar_main), true, getString(R.string.login));

        mTextInputLayoutName = findViewById(R.id.textInputLayoutName);
        mTextInputLayoutPwd = findViewById(R.id.textInputLayoutPassword);

        mEditTextName = findViewById(R.id.editTextName);
        mTextInputLayoutName.setErrorEnabled(true);
        mEditTextPassword = findViewById(R.id.editTextPassword);
        mTextInputLayoutPwd.setErrorEnabled(true);

        keep_pwd = findViewById(R.id.keep_pwd);
        auto_login = findViewById(R.id.auto_login);

        Button loginButton = findViewById(R.id.loginBtn);
        loginButton.setOnClickListener(this);
        Button registerButton = findViewById(R.id.regBtn);
        registerButton.setOnClickListener(this);
        Button findButton = findViewById(R.id.findBtn);
        findButton.setOnClickListener(this);

        mEditTextName.addTextChangedListener(new TextWatcher() {
            @Override/*内容要改变之前调用*/
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                /*从start位置开始，count个字符（空字符是0）将被after个字符替换*/

            }

            @Override/*内容要改变时调用*/
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                /*说明在s字符串中，从start位置开始的count个字符刚刚取代了长度为before的旧文本*/
            }

            @Override/*内容要改变之后调用*/
            public void afterTextChanged(Editable s) {
                //这个方法被调用，那么说明s字符串的某个地方已经被改变。
                checkName(s.toString(), false);
            }
        });

        mEditTextPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkPwd(s.toString(), false);
            }
        });


        SharedPreferences sharedPreferences = getSharedPreferences(Constant.LOGIN_INFO, MODE_PRIVATE);
        String loginInfo = sharedPreferences.getString(Constant.LOGIN_INFO, null);
        UserLogin user = new Gson().fromJson(loginInfo, UserLogin.class);

        if (sharedPreferences.getBoolean(Constant.AUTO_LOGIN, false)) {
            auto_login.setChecked(true);
        }

        if (loginInfo != null && !user.getAccount().isEmpty() && !user.getPwd().isEmpty()) {
            keep_pwd.setChecked(true);
            mEditTextName.setText(user.getAccount());
            mEditTextPassword.setText(user.getPwd());
        }
    }

    private void doLogin(View v) {
        hideSoftInput(v);

        SharedPreferences sharedPreferences = getSharedPreferences(Constant.LOGIN_INFO, MODE_PRIVATE);
        SharedPreferences.Editor spEdit = sharedPreferences.edit();
        //获取输入
        String account = mEditTextName.getText().toString();
        String pwd = mEditTextPassword.getText().toString();

        if (!account.isEmpty() && !pwd.isEmpty()) {
            //使用框架进行数据查询并且核对
            HttpUtils.post(this, url,
                    new HttpUtils().setParam("UserName", account).setParam("UserPwd", pwd), response -> {
                        String request = response.toString();

                        Map map = new Gson().fromJson(request, Map.class);
                        if (map.get("RESULT").equals("S")) {
                            ToastUtils.showToast(this, "登录成功", Toast.LENGTH_SHORT);
                            //自动登录,需要保存账号密码，每次使用的时候与服务器核对更安全
                            if (auto_login.isChecked()) {
                                spEdit.putBoolean(Constant.AUTO_LOGIN, true).apply();
                            } else {
                                spEdit.putBoolean(Constant.AUTO_LOGIN, false).apply();
                            }
                            //记住密码
                            if (keep_pwd.isChecked()) {
                                spEdit.putString(Constant.KEEP_PWD, new Gson().toJson(new UserLogin(account, pwd))).apply();
                            } else {
                                spEdit.remove(Constant.KEEP_PWD).apply();
                            }

                            spEdit.putString(Constant.LOGIN_INFO, new Gson().toJson(new UserLogin(account, pwd))).apply();
                            //跳新的页面
                            startActivity(new Intent(this, SmartTrafficActivity.class));
                            finish();
                        } else {
                            ToastUtils.showToast(this, "登录失败", Toast.LENGTH_SHORT);
                        }
                    }
            );
        } else {
            ToastUtils.showToast(this, "账户或密码为空", Toast.LENGTH_SHORT);
            //提示错误
            if (account.isEmpty()) {
                mTextInputLayoutName.setErrorEnabled(true);
                mTextInputLayoutName.setError("账号账号不能为空");
            } else {
                mTextInputLayoutName.setErrorEnabled(false);
            }
            if (pwd.isEmpty()) {
                mTextInputLayoutPwd.setErrorEnabled(true);
                mTextInputLayoutPwd.setError("密码不能为空");
            } else {
                mTextInputLayoutPwd.setErrorEnabled(false);
            }
        }

    }

    //网络设置
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.network_setting, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                //进入网络设置页面
                Intent intent = new Intent(LoginActivity.this, NetSettingActivity.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.loginBtn) {
            doLogin(v);
        } else if (v.getId() == R.id.regBtn) {
            startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
        } else if (v.getId() == R.id.findBtn) {
            startActivity(new Intent(LoginActivity.this, FindPwdActivity.class));
        }
    }

    private boolean checkPwd(CharSequence pwd, boolean isLogin) {
        if (TextUtils.isEmpty(pwd)) {
            if (isLogin) {
                mTextInputLayoutPwd.setError(getString(R.string.error_pwd_empty));
                return false;
            }
        } else {
            mTextInputLayoutPwd.setError(null);
        }
        return true;
    }

    private boolean checkName(CharSequence name, boolean isLogin) {
        if (TextUtils.isEmpty(name)) {
            if (isLogin) {
                mTextInputLayoutName.setError(getString(R.string.error_login_empty));
                return false;
            }
        } else {
            mTextInputLayoutName.setError(null);
        }
        return true;
    }


    /**
     * 隐藏键盘输入法
     *
     * @param view The view.
     */
    public static void hideSoftInput(final View view) {
        InputMethodManager imm =
                (InputMethodManager) InitApp.getInstance().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0, new ResultReceiver(new Handler()) {
            @Override
            protected void onReceiveResult(int resultCode, Bundle resultData) {
                if (resultCode == InputMethodManager.RESULT_UNCHANGED_SHOWN
                        || resultCode == InputMethodManager.RESULT_SHOWN) {
                    toggleSoftInput();
                }
            }
        });
    }

    /**
     * 软键盘切换
     */
    public static void toggleSoftInput() {
        InputMethodManager imm =
                (InputMethodManager) InitApp.getInstance().getSystemService(Context.INPUT_METHOD_SERVICE);
        //noinspection ConstantConditions
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }

}
